//
//  WmcRecognitionSettingsVM.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/10/18.
//

import Foundation
import YPNetwork

class WmcRecognitionSettingsVM: WmcBaseVM {
    
    var model: WmcWatermarkDetailModel?
    
    var originalContent: [WmcWatermarkOptionModel] = []
    
    init(model: WmcWatermarkDetailModel?) {
        self.model = model
        self.dataSource = model?.fields ?? []
        var temp: [WmcWatermarkOptionModel] = []
        model?.fields.forEach({ optionModel in
            let model = WmcWatermarkOptionModel()
            model.title = optionModel.title
            model.content = optionModel.content
            model.fieldId = optionModel.fieldId
            model.isOpen = optionModel.isOpen
            temp.append(model)
        })
        self.originalContent = temp
    }
    
    public required init() {
        fatalError("init() has not been implemented")
    }
    
    private(set) var dataSource: [WmcWatermarkOptionModel] = []
    
    func saveConfig(_ model: WmcWatermarkDetailModel) {
        if let json: String = WmcUserdefault.object(forKey: .Data.Recognition.configsCache) {
            var array = jsonConvertToArray(json)
            if array.isEmpty {
                if let json = arrayConvertToJson(array: [model]) {
                    WmcUserdefault.save(value: json, forKey: .Data.Recognition.configsCache)
                }
            } else {
                let idx = array.firstIndex { item in
                    return item.wmId == model.wmId
                }
                if let idx = idx {
                    array[idx] = model
                } else {
                    array.append(model)
                }
                if let json = arrayConvertToJson(array: array) {
                    WmcUserdefault.save(value: json, forKey: .Data.Recognition.configsCache)
                }
            }
        } else {
            if let json = arrayConvertToJson(array: [model]) {
                WmcUserdefault.save(value: json, forKey: .Data.Recognition.configsCache)
            }
        }
    }
    
    func restoreData() {
        model?.fields.forEach({ optionModel in
            for originalOptionModel in originalContent {
                if optionModel.fieldId == originalOptionModel.fieldId {
                    optionModel.content = originalOptionModel.content
                    optionModel.isOpen = originalOptionModel.isOpen
                    break
                }
            }
        })
    }

    private func arrayConvertToJson(array: [WmcWatermarkDetailModel]) -> String? {
        var temp: [[String: Any]] = []
        
        array.forEach { model in
            if let dict = model.toJSON() {
                temp.append(dict)
            }
        }
        
        if (!JSONSerialization.isValidJSONObject(temp)) {
            return nil
        }
        var result: String?
        if let data = try? JSONSerialization.data(withJSONObject: temp, options: []), let jsonString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) as String? {
            result = jsonString
        }

        return result
    }

    private func jsonConvertToArray(_ json: String) -> [WmcWatermarkDetailModel] {
        if json == "" || json.count == 0 {
            return []
        }
        var result: [WmcWatermarkDetailModel] = []
        if let data = json.data(using: String.Encoding.utf8), let list = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [Any] {
            for item in list {
                if let dict = item as? [String: Any], let model = WmcWatermarkDetailModel.deserialize(from: dict) {
                    result.append(model)
                }
            }
        }
        return result
    }
}
